package com.atguigu.spzx.gateway.filter;

import com.alibaba.excel.util.ListUtils;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.spzx.common.constant.Constant;
import com.atguigu.spzx.model.entity.user.UserInfo;
import com.atguigu.spzx.model.vo.common.Result;
import com.atguigu.spzx.model.vo.common.ResultCodeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.List;
@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    private AntPathMatcher antPathMatcher=new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String path = exchange.getRequest().getURI().getPath();
        //api接口，异步请求，校验用户必须登录
        if(!antPathMatcher.match("/api/**/auth/**", path)) {
            return chain.filter(exchange);
        }

        List<String> tokenList = exchange.getRequest().getHeaders().get("token");
        if(tokenList==null){
            //报错
            return out(exchange.getResponse(),ResultCodeEnum.LOGIN_AUTH);
            //throw new GuiguException(ResultCodeEnum.LOGIN_AUTH);
        }
        //根据token去数据库里查找
        String token = tokenList.get(0);
        String userInfoJson = redisTemplate.opsForValue().get(Constant.REDIS_USER_LOGIN_TOKEN + token);
        if(!StringUtils.hasText(userInfoJson)){
            //报错
            return out(exchange.getResponse(),ResultCodeEnum.LOGIN_AUTH);
            //throw new GuiguException(ResultCodeEnum.LOGIN_AUTH);
        }

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }

    private Mono<Void> out(ServerHttpResponse response, ResultCodeEnum resultCodeEnum) {
        Result result = Result.build(null, resultCodeEnum);
        byte[] bits = JSONObject.toJSONString(result).getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = response.bufferFactory().wrap(bits);
        //指定编码，否则在浏览器中会中文乱码
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        return response.writeWith(Mono.just(buffer));
    }
}
